package com.css.gdzj.gdzjbxgd.modules.userinfo.service.impl;

import com.css.gdzj.gdzjbxgd.common.util.Constant;
import com.css.gdzj.gdzjbxgd.common.util.R;
import com.css.gdzj.gdzjbxgd.common.util.ServiceUtil;
import com.css.gdzj.gdzjbxgd.common.util.SnowflakeId;
import com.css.gdzj.gdzjbxgd.modules.userinfo.repository.UserInfoNativeRepository;
import com.css.gdzj.gdzjbxgd.modules.userinfo.repository.UserInfoRepository;
import com.css.gdzj.gdzjbxgd.modules.userinfo.repository.entity.QUserInfoEntity;
import com.css.gdzj.gdzjbxgd.modules.userinfo.repository.entity.UserInfoEntity;
import com.css.gdzj.gdzjbxgd.modules.userinfo.service.UserInfoService;
import com.css.gdzj.gdzjbxgd.sys.user.entity.LoginUser;
import com.css.gdzj.gdzjbxgd.sys.user.form.LoginForm;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author z
 * @date 2020-12-11
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

	@Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private UserInfoNativeRepository userInfoNativeRepository;
    @Autowired
    HttpServletRequest request;
    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    private ServiceUtil serviceUtil;

    @Override
    public Map<String,Object> queryUserInfos(String loginName, String userName, String userPost,String userRank,String userLeaderPost,String userUnit,String userLevel, Integer pageNo, Integer pageSize) {
        Map<String,Object> map = new HashMap<>();
        map = this.userInfoNativeRepository.queryUserInfos(loginName,userName,userPost,userRank,userLeaderPost,userUnit,userLevel, pageNo, pageSize);
        return map;
    }

    @Override
    public Map loginGetUserinfo(LoginForm loginForm) {
        QUserInfoEntity qUserInfoEntity = QUserInfoEntity.userInfoEntity;
        List<UserInfoEntity> list = new ArrayList<UserInfoEntity>();
        String sss = DigestUtils.md5Hex(loginForm.getPassword());
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        if (!StringUtils.isEmpty(loginForm.getLoginName()) && !StringUtils.isEmpty(loginForm.getPassword())) {
            userInfoEntity = jpaQueryFactory.selectFrom(qUserInfoEntity).where(qUserInfoEntity.loginName.eq(loginForm.getLoginName()),
                    qUserInfoEntity.loginPassword.eq(DigestUtils.md5Hex(loginForm.getPassword()))).fetchOne();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("data",userInfoEntity);
        return map;
    }

    @Override
    public UserInfoEntity editPassword(String userId, String newPasswordMd5) {
        UserInfoEntity userInfo = this.userInfoRepository.findById(userId).orElse(null);
        if (userId != null){
            userInfo.setLoginPassword(newPasswordMd5);
            this.userInfoRepository.save(userInfo);
        }else {
            return null;
        }
        return userInfo;
    }

    @Override
    public UserInfoEntity controlReport(Map<String, String> params) {
        UserInfoEntity userInfo = this.userInfoRepository.findById(params.get("userId")).orElse(null);
        if (userInfo != null){
            userInfo.setUserReportFlag(params.get("reportFlag"));
            this.userInfoRepository.save(userInfo);
        }else {
            return null;
        }
        return userInfo;
    }

    @Override
    public  UserInfoEntity checkUserLoginName(String userLoginName) {
        QUserInfoEntity qUserInfoEntity = QUserInfoEntity.userInfoEntity;
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        userInfoEntity = jpaQueryFactory.selectFrom(qUserInfoEntity)
                .where(qUserInfoEntity.loginName.eq(userLoginName)).fetchOne();
        return userInfoEntity;
    }
    /*账户递增*/
    @Override
    public String getLoginNameLast(String userLoginName) {
        QUserInfoEntity qUserInfoEntity = QUserInfoEntity.userInfoEntity;
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        int count= jpaQueryFactory.selectFrom(qUserInfoEntity)
                .where(qUserInfoEntity.loginName.like(userLoginName+"%")).fetch().size();
       userInfoEntity = jpaQueryFactory.selectFrom(qUserInfoEntity)
                .where(qUserInfoEntity.loginName.like(userLoginName+"%")).fetchFirst();
        String lastLoginName = userInfoEntity.getLoginName().substring(4,userInfoEntity.getLoginName().length()-1);
       int newLastName=Integer.parseInt(lastLoginName)+count-1;
        String lastFourNum = String.format("%04d", newLastName);
        return lastFourNum;
    }

    @Override
    public void updateUserState(String userId) {
        UserInfoEntity userInfo = this.userInfoRepository.findById(userId).orElse(null);
        String delFlag="0";
        delFlag=Constant.NO_DELETE.equals(userInfo.getDelFlag())?"1":"0";
        userInfoRepository.updateUserState(delFlag,userId);
    }

    @Override
    public Map<String, Object> queryAllUserInfos(String loginName, String userName, String userPoliticalOutlook, String userRank, String userLeaderPost, String userUnit) {
        Map<String,Object> map = new HashMap<>();
        map = this.userInfoNativeRepository.queryAllUserInfos(loginName,userName,userPoliticalOutlook,userRank,userLeaderPost,userUnit);
        return map;
    }

    @Override
    public UserInfoEntity getUserInfo(String id) {
        UserInfoEntity userInfo = this.userInfoRepository.findById(id).orElse(null);
         return userInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfoEntity saveUserInfo(UserInfoEntity userInfo) {
        R userInfoByRequest = serviceUtil.getUserInfoByRequest(request);
        if (userInfoByRequest.getCode().equals("200")) {
            UserInfoEntity loginUser = (UserInfoEntity) userInfoByRequest.get("data");
            String userId = loginUser.getUserId();
            //userId的前四位（单位简称）
            String beginUserID = userId.substring(0, userId.indexOf('_') + 1);
            //userId的后面序号
            String endUserID = userId.substring(userId.indexOf('_') + 1);
            //获取单位下的size
            QUserInfoEntity qUserInfoEntity = QUserInfoEntity.userInfoEntity;
            UserInfoEntity userInfoEntity = new UserInfoEntity();
            int count= jpaQueryFactory.selectFrom(qUserInfoEntity)
                    .where(qUserInfoEntity.userId.like(beginUserID+"%")).fetch().size();
            int num = Integer.parseInt(endUserID) + count;
            String newUserId = beginUserID + num;
            /*            String uuid = SnowflakeId.getId();*/
            userInfo.setUserId(newUserId);
            userInfo.setLoginPassword(DigestUtils.md5Hex("abc123"));
            userInfo.setUserReportFlag("1");//填报开关：0：不填报 1：填报
            userInfo.setUserLevel("0");//非管理员（大管理员2、管理员1、普通用户0）
            userInfo.setDelFlag("0");
            userInfo.setUserIsReport("1");
            this.userInfoRepository.save(userInfo);
            return userInfo;
        }else{
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfoEntity updateUserInfo(UserInfoEntity userInfo) {
        this.userInfoRepository.save(userInfo);
        return userInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserInfos(List<String> ids) {
        List<UserInfoEntity> userInfoList = this.userInfoRepository.findAllById(ids);
        if(!StringUtils.isEmpty(userInfoList) && userInfoList.size() > 0) {
            for(UserInfoEntity userInfo : userInfoList) {
                this.userInfoRepository.delete(userInfo);
            }
        }
    }

    @Override
    public void exportExcel(String userName, String userUnit, HttpServletResponse response) {

    }

    @Override
    public String uploadFile(MultipartFile file, HttpServletResponse response) {
        return null;
    }

  /*  @Override*/
    /*public void exportExcel(String userName, String userUnit, HttpServletResponse response){
        List<BxgdReportContralEntity> userInfoList = userInfoNativeRepository.queryUserInfo(userName,userUnit);
        List<UserInfoExportExcelVO> excelVos = new ArrayList<>();

        userInfoList.forEach(e->{
            UserInfoExportExcelVO userInfoExcelVo = new UserInfoExportExcelVO();
            BeanUtils.copyProperties(e,userInfoExcelVo);
            excelVos.add(userInfoExcelVo);
        });
        *//*Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, "user_info"), UserInfoExportExcelVO.class, excelVos);
        PlatformDownloadUtils.exportExcel(workbook, "user_info.xls", response);*//*

    }*/

  /*  @Override*/
    /*public String uploadFile(MultipartFile file, HttpServletResponse response) {
        return null;
    }*/
    /*@Override*/
    /*public String uploadFile(MultipartFile file, HttpServletResponse response) {
    try{
        StringBuilder returnMsg = new StringBuilder();
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setNeedVerify(true);

        ExcelImportResult<UserInfoExcelVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(),UserInfoExcelVO.class,params);
        List<UserInfoExcelVO> userInfoExcelVoList = result.getFailList();
        for(int i = 0;i<userInfoExcelVoList.size();i++){
            UserInfoExcelVO userInfoExcelVo = userInfoExcelVoList.get(i);
            String msg = userInfoExcelVo.getErrorMsg();
            Integer num = userInfoExcelVo.getRowNum();
            if(PlatformObjectUtils.checkFieldAllNull(userInfoExcelVo)){
            userInfoExcelVoList.remove(i);
            i--;
        }else{
            userInfoExcelVo.setRowNum(num);
            userInfoExcelVo.setErrorMsg(msg);
                }
        }

        List<BxgdReportContralEntity>  dataEntityList = new ArrayList<>();
        List<UserInfoExcelVO> list = result.getList();
            list.forEach(e->{
                BxgdReportContralEntity dataEntity = new BxgdReportContralEntity();
                BeanUtils.copyProperties(e,dataEntity);
                dataEntity.setId(UUIDGenerator.getUUID());
                dataEntity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                dataEntity.setCreateUser(PlatformSessionUtils.getUserId());
                dataEntityList.add(dataEntity);
            });
    userInfoRepository.saveAll(dataEntityList);
    int successListSize = list.size() - userInfoExcelVoList.size();
    returnMsg.append("成功导入" + successListSize + "条，失败" + userInfoExcelVoList + "条");

    for (UserInfoExcelVO entity : result.getFailList()) {
        String msg = "";
        returnMsg.append("第" + entity.getRowNum() + "行" + entity.getErrorMsg() + "<br/>");
        returnMsg.append(msg);
    }
    return returnMsg.toString();
    }catch (Exception e){
        e.printStackTrace();
    return "导入失败，请检查数据正确性";

    }
   }*/

}
